package org.phantom.securityframework.datapermission.internal;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.phantom.securityframework.datapermission.DataProvider;
import org.phantom.securityframework.datapermission.DataProviderResolver;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


/**
 * 数据提供解析器默认实现
 * 监听ServiceListener,根据
 * 			<osgi:service-properties>
				<entry key="filter" value="userManager"/>
			</osgi:service-properties>的filter属性来获取对应的DataProvider
 * @author apple
 *
 */
@Service("dataProviderResolverDefaultImpl")
public class DataProviderResolverDefaultImpl implements DataProviderResolver,ServiceListener {


	
	@Resource(name="simpleSqlDataProvider")
	private DataProvider simpleSqlDataProvider = null;
	@Resource(name="mapperDataProvider")
	private DataProvider mapperDataProvider = null;
	
	private Map<String,DataProvider> services = new HashMap<String,DataProvider>();
	private BundleContext bundleContext = null;
	
	@PostConstruct
	public void init(){
		this.services.put(DEFAULT_PROVIDER, simpleSqlDataProvider);
		this.services.put(MAPPER_PROVIDER, mapperDataProvider);
	}
	@Override
	public void serviceChanged(ServiceEvent event) {
		if(event.getType() == ServiceEvent.REGISTERED){
			Object o = bundleContext.getService(event.getServiceReference());
			if(o instanceof DataProvider){
				String key = StringUtils.trimWhitespace(event.getServiceReference().getProperty("filter").toString());
				services.put(key, (DataProvider) o);
			}
		}
	
	}


	@Override
	public DataProvider resolveDataProvider(String filter) {
		return this.services.get(filter);
	}

}
